//
//  BSBluetoothSingleton.m
//  SuoSiApp
//
//  Created by zhang on 16/4/11.
//  Copyright © 2016年 Ym. All rights reserved.
//

#import "FMDB.h"
#include <stdio.h>
#include <unistd.h>
#include "ecg_filter.h"
#include "hrate_detect.h"

#define TEST_LEN 375
#define Hrate_TEST_LEN 1250
/**     **/

#import "BStripleECGViewController.h"

#import <AudioToolbox/AudioToolbox.h>
#import "BSBluetoothSingleton.h"

//int n = 0;
static SystemSoundID shake_sound_male_id = 0;



@interface BSBluetoothSingleton ()
{
//实例变量
    //三通道的结构体 初始化的时候用到
   ECG_HND *ECG_INIT[3];
    
}

//接收临时数据
@property (nonatomic, strong)NSMutableArray *tepArr;


@property (nonatomic, assign) id INITECG;;


@property (nonatomic,strong) FMDatabase *db;

//当前蓝牙的帧数
@property (nonatomic, assign) int currentCount;

@end

@implementation BSBluetoothSingleton

+ (BSBluetoothSingleton *)shareBlutooth{

    static BSBluetoothSingleton *bluetoothHandle = nil;
//    if (bluetoothHandle == nil) {
//        bluetoothHandle = [[BSBluetoothSingleton alloc]init];
//    }
    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{
         bluetoothHandle = [[BSBluetoothSingleton alloc]init];
        
    });
    return bluetoothHandle;
}

- (instancetype)init{

    self = [super init];
    if (self) {
        self.isConnected = NO;
        [self creatDataFile];
        [self ECGDatalist];
        _isInit = NO;
           }
    return self;
}
// 懒加载
- (NSMutableArray *)peripherals{
    
    if (!_peripherals) {
        _peripherals = [[NSMutableArray alloc]init];
    }
    return _peripherals;
}
- (NSMutableArray *)dataArrOnce1{
    if (!_dataArrOnce1) {
        _dataArrOnce1 = [[NSMutableArray alloc]init];
    }
    return _dataArrOnce1;
}
- (NSMutableArray *)dataArrOnce2{
    if (!_dataArrOnce2) {
        _dataArrOnce2 = [[NSMutableArray alloc]init];
    }
    return _dataArrOnce2;
}
- (void)changeIsconect{

    self.isConnected = YES;
}

#pragma mark 第一步
- (void)findBluetooth{

    
    //        设置代理
    self.manager = [[CBCentralManager alloc]initWithDelegate:self queue:nil];
    self.manager.delegate = self;
    
    //        2.利用中心设备 扫描
    //        如果给定数组代表只扫描指定设备
    [self.manager scanForPeripheralsWithServices:nil options:nil];
    //[self.tableview reloadData];

}
#pragma mark 后台用UUID扫描 连到了 就直接连上
- (void)findBluetoothWithUUID:(NSString *)uuid{
    
    if (_isConnected == NO) {
        [self findBluetooth];
        self.uuiduuid = uuid;

    }
}

#pragma mark 第二步  扫描外设
#pragma mark -- CBCentralmanagerDelegate
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI{
    NSLog(@"搜到的蓝牙的identifier >>%@",peripheral.identifier);
    NSString *Str = [NSString stringWithFormat:@"%@",peripheral.identifier];
    //如果保存的UUID 就是找到的这个 直接连
    NSString *temstr = [Str substringWithRange:NSMakeRange(Str.length - 36, 36)];
    [PKRequestManager showAlertView:temstr];
    if ([temstr isEqualToString:_uuiduuid]) {
        [self.manager connectPeripheral:peripheral options:nil];
    }
    //    保存扫描到得外部设备
    //    但是要判断这个这个设备 是不是已经找到过 存储新发现的设备
    peripheral.delegate  = self;
    self.perpheral = peripheral;
    NSLog(@"信号强度 >>  %@",RSSI);
//    self.perpheral.delegate = self;
#pragma mark 将UUID转换为名字
       if ((![self.peripherals containsObject:peripheral]&&peripheral.name)) {
        [self.peripherals addObject:peripheral];

    }
//    self.bsblueVC.peripherals = self.peripherals;
    [self.bsblueVC.tableview reloadData];
}
#pragma mark 第三步 连接外设
- (void)connectPerpheralWithIndexpathrow:(NSInteger )row{



    self.perpheral = self.peripherals[row];
    NSLog(@"开始链接蓝牙> %@",self.perpheral.name);
    [self.manager connectPeripheral:self.perpheral options:nil];

}
//    链接外设成功调用
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral{
    [self.manager stopScan];
//    扫描外设中得服务
    [peripheral discoverServices:nil];
    NSLog(@"链接成功");
    self.perpheral = peripheral;
//    链接成功 进行赋值
    NSString *Str = [NSString stringWithFormat:@"%@",peripheral.identifier];
    //如果保存的UUID 就是找到的这个 直接连
    NSString *temstr = [Str substringWithRange:NSMakeRange(Str.length - 36, 36)];
    
    self.uuiduuid = temstr;
    
    
    [self changeIsconect];
    [self ECGDatalist];
    
#pragma mark 创建保存data的文件夹
    [self creatDataFile];
    
#pragma 连接成功 应该调到三通道界面

    [peripheral readRSSI];
    

    
    BStripleECGViewController *triVC = [[BStripleECGViewController alloc]init];
    [self.bsblueVC.navigationController pushViewController:triVC animated:YES];
    
    
}
//    链接外设失败调用
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error{
    
    [self.peripherals removeObject:peripheral];
    
    [self.bsblueVC.tableview reloadData];
    
    self.isConnected = NO;
#pragma mark  连接失败的处理
    
    [self warningForDisconnected];
    
    //    断开连接重新扫描已经连接过的设备
    
    NSString *uuid =   self.uuiduuid;

    self.RSSIValue = 0;
    self.batVolValue = 0;
    self.heartRate = 0 ;
    NSLog(@"断开连接");
     self.getsignal();
    [self findBluetoothWithUUID:uuid];
    
    
}

#pragma mark 第四步
//只要扫到服务就会调用
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{
    
    NSLog(@"扫描服务");
    //    获取外设中 所有扫描得到的服务
    NSArray *services = peripheral.services;
    for (CBService *service in services) {
        //  找到需要的服务
        NSLog(@"%@",service.UUID.UUIDString);
        NSLog(@"服务identifierUUID >> %@",service.UUID);
        //  [self showTheAlertViewWithMessage:@"拿到对应的服务了"];
        //        拿到服务里的所有特征 应该找特定的
        [peripheral discoverCharacteristics:nil forService:service];
        
        }
}
//只要扫描到特征 就会调用
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error{
    
    NSLog(@"扫描特征");
    //    拿到服务中所有的特征
    //    NSArray *characteristics = service.characteristics;
    //    遍历这个特征 拿到需要的特征 然后处理
    
    if (error)
    {
     //   NSLog(@"error Discovered characteristics for %@ with error: %@", service.UUID, [error localizedDescription]);
        return;
    }
    
//    for (CBCharacteristic *characteristic in service.characteristics)
//    {
//        // characteristic.
//      //  NSLog(@"service:%@ 的 Characteristic: %@",service.UUID,characteristic.UUID);
//    }
    
    //获取Characteristic的值，读到数据会进入方法：-(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
    for (CBCharacteristic *characteristic in service.characteristics){
        {
            [peripheral readValueForCharacteristic:characteristic];
        }
    }
    
    //搜索Characteristic的Descriptors，读到数据会进入方法：-(void)peripheral:(CBPeripheral *)peripheral didDiscoverDescriptorsForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
    
    //    获取特征里面的描述值 并且订阅 这个特征
    for (CBCharacteristic *characteristic in service.characteristics){
        [peripheral discoverDescriptorsForCharacteristic:characteristic];
        [peripheral setNotifyValue:YES forCharacteristic:characteristic];
    }
    
}
- (void)peripheral:(CBPeripheral *)peripheral didReadRSSI:(NSNumber *)RSSI error:(NSError *)error{
    if (self.isConnected == YES) {
        self.RSSIValue =  abs([RSSI intValue]);
        NSLog(@"%ld",(long)[BSBluetoothSingleton shareBlutooth].RSSIValue);

        self.getsignal();
        
    } else {
        self.RSSIValue =  0;
        NSLog(@"%ld",(long)[BSBluetoothSingleton shareBlutooth].RSSIValue);

    }
  
}
#pragma mark 第五步
//与外设数据做交互
//获取的charateristic的值  特征里面的值 发生变化 这个值 使我们 需要获取的
-(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
    
    //打印出characteristic的UUID和值
    //!注意，value的类型是NSData，具体开发时，会根据外设协议制定的方式去解
 
    if (!_NSMutableDataNOW) {
        _NSMutableDataNOW = [[NSMutableData alloc]init];
    }
    [_NSMutableDataNOW appendData:characteristic.value];
    
    if (_NSMutableDataNOW.length > 10000) {
        [_NSMutableDataNOW replaceBytesInRange:NSMakeRange(0, _NSMutableDataNOW.length) withBytes:NSInternalInconsistencyException];
    }
    if (characteristic.value) {
        NSString *str = [NSString stringWithFormat:@"%@",characteristic.value];
        NSLog(@"%@",str);
//        判断 是不是 0x83
        if (!_tepArr) {
            _tepArr = [[NSMutableArray alloc]init];
            
        }
        
#pragma mark 这里以后需要加 电极脱落提示
        if ([self valueIsequaToString83:str] &&str.length > 35) {//[self valueIsequaToString83:str] &&
//            用于补零的字符串
            NSString *str0 = @"000000000000000000000000000000000000000000000000000000000000";
            str0 = [str0 substringWithRange:NSMakeRange(0, str.length)];
            [str stringByReplacingCharactersInRange:NSMakeRange(0, str.length) withString:str0];
#pragma mark 分别解析三个通道的数据
            int chanel = [self valueIsequaToString83:str];
          
            if (chanel == 1) { // 0x80
//                需要判断是不是要补帧
                static int  root = 0;
//                帧数差
                  int n = 0;
                int current = [self isNeedTofixdata:characteristic.value];
                if (root == 0) {
                    _chanel1count = current;
                    root ++;
                
                } else {
                    int next = [self isNeedTofixdata:characteristic.value];

                    if (next > _chanel1count) {
                        n = (next - _chanel1count)/2 - 1;
                    } else {
                        n = next - _chanel1count + 254;
                        n /= 2 - 1;
                    }
                    for (int i = 0; i < n; i++) {
                        [self convertString:str0];
                    }
                }

               _chanel1count = [self isNeedTofixdata:characteristic.value];

                 [self convertString:str];
                
                
            }
            if (chanel == 2) {// 0 x90
                
                //                需要判断是不是要补帧
                static int  root2 = 0;
                //                帧数差
                int n = 0;
                int current = [self isNeedTofixdata:characteristic.value];
                if (root2 == 0) {
                    _chanel2count = current;
                    root2 ++;
                    
                } else {
                    int next = [self isNeedTofixdata:characteristic.value];
                    
                    if (next > _chanel2count) {
                        n = (next - _chanel2count)/2 - 1;
                    } else {
                        n = next - _chanel2count + 254;
                        n /= 2 - 1;
                    }
                    for (int i = 0; i < n; i++) {
                        [self convertString2:str0];
                    }
                }
                
                _chanel2count = [self isNeedTofixdata:characteristic.value];
                
                [self convertString2:str];
            }
            if (chanel == 3) { // 0xa0
                
                //                需要判断是不是要补帧
                static int  root3 = 0;
                //                帧数差
                int n = 0;
                int current = [self isNeedTofixdata:characteristic.value];
                if (root3 == 0) {
                    _chanel3count = current;
                    root3 ++;
                    
                } else {
                    int next = [self isNeedTofixdata:characteristic.value];
                    
                    if (next > _chanel3count) {
                        n = (next - _chanel3count)/2 - 1;
                    } else {
                        n = next - _chanel3count + 254;
                        n /= 2 - 1;
                    }
                    for (int i = 0; i < n; i++) {
                        [self convertString3:str0];
                    }
                }
                
                _chanel3count = [self isNeedTofixdata:characteristic.value];
                
                
              [self convertString3:str];
            }
            
            [_tepArr addObject:characteristic.value];
            
            if (_tepArr.count / 100 == 1) {
                [peripheral readRSSI];
                
                NSArray *tempArr = [NSArray arrayWithArray:_tepArr];
                [_tepArr removeAllObjects];

//                开辟线程写文件 保证数据库操作 和 ui刷新不冲突
                //                开始保存文件
                if ([BSUserSGton userHandle].memoryValue > 200) {
                    [self creatECGDataTofileWithBlueToothdata:tempArr];

                }else{
#pragma mark 提示内存不足
                    [PKRequestManager showAlertView:@"手机内存不足,请清理内存后才能存储数据"];
                }
            }
        }
        
        else if([self valueIsequaToString8x:str] && str.length > 35){
        //将 str 全部值为零
            NSString *str0 = @"000000000000000000000000000000000000000000000000000000000000";
            str0 = [str0 substringWithRange:NSMakeRange(0, str.length)];
            [str stringByReplacingCharactersInRange:NSMakeRange(0, str.length) withString:str0];
            [self convertString:str0];
        
        }
        

        if ([self valueIsequaToStringf:str] && str.length > 35) {
            [self getValueOfV:str];
            [self getValueOfTemper:str];
        }
        
    
    }
    
    
    
}
#pragma 提取方法 判断是否有电极脱落


- (void)convertStringWithHeader0x8x:(NSString *)str{



}




//搜索到Characteristic的Descriptors
-(void)peripheral:(CBPeripheral *)peripheral didDiscoverDescriptorsForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
    
    //打印出Characteristic和他的Descriptors
    NSLog(@"characteristic uuid:%@",characteristic.UUID);
//    for (CBDescriptor *d in characteristic.descriptors) {
//        NSLog(@"Descriptor uuid:%@",d.UUID);
//    }
    
}
//获取到Descriptors的值
-(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForDescriptor:(CBDescriptor *)descriptor error:(NSError *)error{
    //打印出DescriptorsUUID 和value
    //这个descriptor都是对于characteristic的描述，一般都是字符串，所以这里我们转换成字符串去解析
//    NSLog(@"characteristic uuid:%@  value:%@",[NSString stringWithFormat:@"%@",descriptor.UUID],descriptor.value);
    
}
#pragma mark 第六步
//订阅特征
-(void)peripheralManager:(CBPeripheralManager *)peripheralMamager central:(CBCentral *)central didSubscribeToCharacteristic:(CBCharacteristic *)characteristic{

}
//设置通知
-(void)notifyCharacteristic:(CBPeripheral *)peripheral
             characteristic:(CBCharacteristic *)characteristic{
    //设置通知，数据通知会进入：didUpdateValueForCharacteristic方法
    [peripheral setNotifyValue:YES forCharacteristic:characteristic];
    
}
//取消通知
-(void)cancelNotifyCharacteristic:(CBPeripheral *)peripheral
                   characteristic:(CBCharacteristic *)characteristic{
    
    [peripheral setNotifyValue:NO forCharacteristic:characteristic];
}

#pragma mark 第七步



// 这 是检测到蓝牙状态发生变化 再次 开启蓝牙 还是要进行扫描
- (void)centralManagerDidUpdateState:(CBCentralManager *)central{
    
    NSLog(@"检测代理方法");
    if (central.state == 5) {
        [self.manager scanForPeripheralsWithServices:nil options:nil];
        
        NSLog(@"%ld，%@", (long)central.state, central);
    }
}


// 创建保存data的方法
- (void)creatDataFile{
    //打印沙河路径
    
    NSArray *documents = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    
    NSString *path = @"/ECGData";
    
    NSString *filePath = [documents[0] stringByAppendingString:path];
    //    保存的文件名
    self.fileManager = [NSFileManager defaultManager];
    if (!    [_fileManager fileExistsAtPath:filePath ]
        ) {
        
        BOOL isCreat = [_fileManager createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];
        if (!isCreat) {
            [_fileManager createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];
        }
        NSLog(@"%@ >>  @",filePath);
       
    }
     self.filePath = filePath;
    
}

//- (void)writeDataTofile:(NSMutableArray *)arr{
//    
//    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
//    //    设置时间格式
//    formatter.dateFormat = @"yyyyMMddHHmm";
//    
//    NSString *dateFormatter = [formatter stringFromDate:[NSDate date]];
//    NSString *fileName = [NSString stringWithFormat:@"/%@.dat",dateFormatter];
//    NSString *fileDataPath = [_filePath stringByAppendingString:fileName];
//    
//    if ( ![_fileManager fileExistsAtPath:fileDataPath]
//        ) {
//        [_fileManager createFileAtPath:fileDataPath contents:nil attributes:nil];
//    }
//    
//    //    for (int i = 0; i < arr.count; i++) {
//    //        [self.fileHandle seekToEndOfFile];
//    //        NSData *data = arr[i];
//    //        [self.fileHandle writeData:data];
//    //    }
//    NSString *str = @"123";
//    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding ];
//    [self.fileHandle writeData:data];
//    
//    [self.fileHandle seekToEndOfFile];
//    [self.fileHandle writeData:data];
//    
//    [self.fileHandle closeFile];
//    //
//    
//}


//读取文件的内容/Users/zhang/Desktop/ECGData/201604281453.dat
//- (void)readContent{
//    
//    //    NSString *str = [NSString s];
//    //    NSData *data = [NSData dataWithContentsOfFile:self.dataSourcePath];
//    
//    NSString *str = [NSString stringWithContentsOfFile:self.dataSourcePath encoding:NSUTF8StringEncoding error:nil];
//    NSLog(@">>>>>>%@",str);
//}

//判断字符串 是不是83开头的
- (int)valueIsequaToString83:(NSString *)str{
 NSString *cmp1 = @"80";
    NSString *cmp2 = @"90";
    NSString *cmp3 = @"a0";

 NSString *head = @"";
    if (str.length > 10) {
     head = [str substringWithRange:NSMakeRange(1, 2)];

    }
    if ([head isEqualToString:cmp1]) {
        return 1;
    }
    if ([head isEqualToString:cmp2]) {
        return 2;
    }
    if ([head isEqualToString:cmp3]) {
        return 3;
    }
    return 0;
}
- (BOOL)valueIsequaToString8x:(NSString *)str{
    NSString *head = @"";
    if (str.length > 10) {
        head = [str substringWithRange:NSMakeRange(1, 2)];
    }
    if ([head isEqualToString:@"83"]) {
        return YES;
    }
    if ([head isEqualToString:@"81"]) {
        return YES;
    }
    if ([head isEqualToString:@"82"]) {
        return YES;
    }
    return NO;
}
//判断字符串 是不是F开头的  第17个数 是电压值
- (BOOL)valueIsequaToStringf:(NSString *)str{
    NSString *cmp = @"f";
    NSString *head = [str substringWithRange:NSMakeRange(1, 1)];
    
    if ([head isEqualToString:cmp]) {
        return YES;
    } else {
        return NO;
    }
}

- (CGFloat)getValueOfV:(NSString *)stt{
    
//    里面有四个空格 所以是 17 * 2 + 4
    NSString *str = [stt substringWithRange:NSMakeRange(39, 2)];

    int int_ch1 = 0;

    for (int i = 0; i < str.length; i++) {
         unichar hex_char1 = [str characterAtIndex:i];
    
       
    if(hex_char1 >= '0' && hex_char1 <='9')
        
        int_ch1 = (hex_char1-48)*16;   //// 0 的Ascll - 48
    
    else if(hex_char1 >= 'A' && hex_char1 <='F')
        
        int_ch1 = (hex_char1-55)*16; //// A 的Ascll - 65
    
    else
        
        int_ch1 = (hex_char1-87)*16; //// a 的Ascll - 97
    
    i++;
    
    unichar hex_char2 = [str characterAtIndex:i]; ///两位16进制数中的第二位(低位)
    //
    int int_ch2  = 0;
    
    if(hex_char2 >= '0' && hex_char2 <='9')
        
        int_ch2 = (hex_char2-48); //// 0 的Ascll - 48
    
    else if(hex_char1 >= 'A' && hex_char1 <='F')
        
        int_ch2 = hex_char2-55; //// A 的Ascll - 65
    
    else
        
        int_ch2 = hex_char2-87; //// a 的Ascll - 97
    
    int_ch1 = int_ch1+int_ch2;

    
}
//    NSLog(@"转换的电压 >> %.2F",int_ch1/50.0);
    self.batVolValue = int_ch1/50.00;
    [self.perpheral readRSSI ];

    return int_ch1/50.0;

}

#pragma mark 获取温度
- (CGFloat)getValueOfTemper:(NSString *)stt{
    
    //    里面有四个空格 所以是 17 * 2 + 4
    NSString *str = [stt substringWithRange:NSMakeRange(stt.length - 9, 2)];
    
    int int_ch1 = 0;
    
    for (int i = 0; i < str.length; i++) {
        unichar hex_char1 = [str characterAtIndex:i];
        
        
        if(hex_char1 >= '0' && hex_char1 <='9')
            
            int_ch1 = (hex_char1-48)*16;   //// 0 的Ascll - 48
        
        else if(hex_char1 >= 'A' && hex_char1 <='F')
            
            int_ch1 = (hex_char1-55)*16; //// A 的Ascll - 65
        
        else
            
            int_ch1 = (hex_char1-87)*16; //// a 的Ascll - 97
        
        i++;
        
        unichar hex_char2 = [str characterAtIndex:i]; ///两位16进制数中的第二位(低位)
        //
        int int_ch2  = 0;
        
        if(hex_char2 >= '0' && hex_char2 <='9')
            
            int_ch2 = (hex_char2-48); //// 0 的Ascll - 48
        
        else if(hex_char1 >= 'A' && hex_char1 <='F')
            
            int_ch2 = hex_char2-55; //// A 的Ascll - 65
        
        else
            
            int_ch2 = hex_char2-87; //// a 的Ascll - 97
        
        int_ch1 = int_ch1+int_ch2;
        
        
    }
//    NSLog(@"电池温度 >> %.2F",int_ch1/5.0);
    
    self.tempValue = (CGFloat)int_ch1/5.0;
    return int_ch1/5.0;
    
}
- (int )isNeedTofixdata:(NSData *)data{
    NSData *DA = [data subdataWithRange:NSMakeRange(1, 1)];
    NSString *DAS = [[NSString stringWithFormat:@"%@",DA] substringWithRange:NSMakeRange(1, 2)];
    int A = [self convert2StringToInt:DAS];

    return A;
}


//将16进制的value 转为10进制
- (NSMutableArray *)convert16Data:(NSData *)data{

    //    转换的24个点
    NSMutableArray *pointArr = [NSMutableArray array];
    
//    从第二个字节开始 连续三个字节  ABC
    for (int i = 2; i < data.length - 1;  i += 3) {
        NSData *DA = [data subdataWithRange:NSMakeRange(2, 1)];
        NSData *DB = [data subdataWithRange:NSMakeRange(3, 1)];
        NSData *DC = [data subdataWithRange:NSMakeRange(4, 1)];
  
        NSString *DAS = [[NSString stringWithFormat:@"%@",DA] substringWithRange:NSMakeRange(1, 2)];
        NSString *DBS = [[NSString stringWithFormat:@"%@",DB]substringWithRange:NSMakeRange(1, 2)];
        NSString *DCS = [[NSString stringWithFormat:@"%@",DC]substringWithRange:NSMakeRange(1, 2)];
        
//        得到ABC
        int A = [self convert2StringToInt:DAS];
        int B = [self convert2StringToInt:DBS];
        int C = [self convert2StringToInt:DCS];

//        转到 ABCD
        int aa = 0;
        int bb = 0;
        int cc = 0;
        int dd = 0;
//        byte restoreA = (byte) ((A & 0x80) | ((A & 0x7C) >>2));
//        byte restoreB = (byte) (((A & 0x03) << 6) | ((B & 0xF0)>>2));
//        byte restoreC = (byte) (((B & 0x08) << 4) | ((B & 0x07) << 2) | ((C & 0xC0) >> 6));
//        byte restoreD = (byte) ((C & 0x3F) << 2);
        aa = ((A & 0x80) | ((A & 0x7c)>>2));
        
        bb = (((A & 0x03) << 6) | ((B & 0xf0) >> 2));
        cc = (((B & 0x08)<< 4) | ((B & 0x07) << 2) | ((C & 0xc0) >> 6));
        dd = ((C & 0x3f) << 2);
        
        int a = 0x12;

        int num1 = ((aa << 8) | bb);
        int num2 = ((cc << 8) | dd);
        [pointArr addObject:[NSNumber numberWithInt:num1]];
        [pointArr addObject:[NSNumber numberWithInt:num2]];
       
        

//        转换成 整数
    }
    return pointArr;
}


//   将16进制的字符串 转为10进制的数
- (void)convertString:(NSString* )hexString {
    NSMutableArray *numberArr = [NSMutableArray array];
    //    转换的24个点
    NSMutableArray *pointArr = [NSMutableArray array];

    if (!_bluePointdrawArr) {
        _bluePointdrawArr = [[NSMutableArray alloc]init];

    }
        //    初始的18点
           int j = 0;
        //  长度 - 1  因为最后一个字符是 '>' 不要的
        for(int i = 5;i < [hexString length] - 1;i ++)
            
        {
            int int_ch; /// 两位16进制数转化后的10进制数
            unichar hex_char1 = [hexString characterAtIndex:i]; ////两位16进制数中的第一位(高位*16)
            
            //        碰到空格 置为空
            if (hex_char1 == ' ') {
                hex_char1 = [hexString characterAtIndex:1 + i];
                //            NSLog(@"碰到一个空格");
                i++;
            }
            
            int int_ch1;
            
            if(hex_char1 >= '0' && hex_char1 <='9')
                
                int_ch1 = (hex_char1-48)*16;   //// 0 的Ascll - 48
            
            else if(hex_char1 >= 'A' && hex_char1 <='F')
                
                int_ch1 = (hex_char1-55)*16; //// A 的Ascll - 65
            
            else
                
                int_ch1 = (hex_char1-87)*16; //// a 的Ascll - 97
            
            i++;
            
            unichar hex_char2 = [hexString characterAtIndex:i]; ///两位16进制数中的第二位(低位)
            //
            int int_ch2;
            
            if(hex_char2 >= '0' && hex_char2 <='9')
                
                int_ch2 = (hex_char2-48); //// 0 的Ascll - 48
            
            else if(hex_char1 >= 'A' && hex_char1 <='F')
                
                int_ch2 = hex_char2-55; //// A 的Ascll - 65
            
            else
                
                int_ch2 = hex_char2-87; //// a 的Ascll - 97
            
            int_ch = int_ch1+int_ch2;
            //
            
            
            [numberArr addObject:[NSNumber numberWithInt:int_ch]];
            j++;
            
        }
        //    这数组中得18个点 三三一组 组成四个点 然后合成24个点
        //    然后就是24个点 两两一组 组成12个点
        
        //    A'
        int aa = 0;
        int bb = 0;
        int cc = 0;
        int dd = 0;
        if (numberArr.count) {
            for (int i = 0; i <= numberArr.count - 3; i = i + 3) {
                
                int a = [numberArr[i] intValue];
                int b = [numberArr[i + 1] intValue];
                int c = [numberArr[i + 2] intValue];
                
                aa = ((a & 0x80) | ((a & 0x7c)>>2));
                //            修改aa
                if (aa != 0) {
                    aa = (0xe0)|((a & 0x7c)>>2);
                    
                } else {
                    aa = ((a & 0x7c)>>2);
                }
                
                bb = (((a & 0x03) << 6) | ((b & 0xf0) >> 2));
                cc = (((b & 0x08)<< 4) | ((b & 0x07) << 2) | ((c & 0xc0) >> 6));
                //            修改cc
                if (cc != 0) {
                    cc = (0xe0 | (b & 0x07)<<2) | ((c & 0xc0)>>6);
                } else {
                    cc = ((b & 0x07)<<2) | ((c & 0xc0)>>6);
                }
                
                dd = ((c & 0x3f) << 2);
                
                //            [pointArr addObject:[NSNumber numberWithInt:aa]];
                //            [pointArr addObject:[NSNumber numberWithInt:bb]];
                //            [pointArr addObject:[NSNumber numberWithInt:cc]];
                //            [pointArr addObject:[NSNumber numberWithInt:dd]];
                int num1 = ((aa << 8) | bb);
                int num2 = ((cc << 8) | dd);
                
                [pointArr addObject:[NSNumber numberWithInt:num1]];
                [pointArr addObject:[NSNumber numberWithInt:num2]];
            }
        }
        //    pointArr 包含了24个点 这个要转换成12个数
        if (pointArr[5]) {
            [pointArr removeObjectAtIndex:5];
            
        }
        if (pointArr[10]) {
            [pointArr removeObjectAtIndex:10];
            
        }


    NSArray *tempArr = [NSArray arrayWithArray:pointArr];
    
    [_bluePointdrawArr addObjectsFromArray:tempArr];
    if (_bluePointdrawArr.count / TEST_LEN >= 1) {
        NSArray *arr = [_bluePointdrawArr subarrayWithRange:NSMakeRange(0, TEST_LEN)];
        NSMutableArray *ECGarr = [NSMutableArray arrayWithArray:[self ECGmain:arr chanel:0]];
        if (!_chanel1Arr) {
            _chanel1Arr = [[NSMutableArray alloc]init];
        }
        [_chanel1Arr addObjectsFromArray:ECGarr];
        
        
//        如果缓存的数据太多 就删除一部分 保证显示的尽量都是实时数据
        if (_chanel1Arr.count > 2000) {
            [_chanel1Arr removeObjectsInRange:NSMakeRange(0, _chanel1Arr.count/2)];
        }
//        通过数据 计算心率 数据长度 不足1250 计算不出来心率 所以 对ECGarr 进行处理
        if (!_HrateArr) {
            _HrateArr = [NSMutableArray array];
        }
        if (_HrateArr.count < Hrate_TEST_LEN) {
            [_HrateArr addObjectsFromArray:ECGarr];
        } else {
            double ecgData[Hrate_TEST_LEN];
            for (int i = 0; i < Hrate_TEST_LEN; i++) {
                ecgData[i] = [_HrateArr[i] doubleValue];
            }
            
            self.heartRate = hrate_detect(ecgData,Hrate_TEST_LEN);
            //        NSLog(@"获取的当前心率>> %d",self.heartRate);
            if (self.heartRate < 0) {
                _heartRate = 0 ;
            }
            [_HrateArr removeObjectsInRange:NSMakeRange(0,Hrate_TEST_LEN )];
            
        }

        [_bluePointdrawArr removeObjectsInRange:NSMakeRange(0, TEST_LEN)];
    }
}

#pragma mark 2222222
//   将16进制的字符串 转为10进制的数
- (void)convertString2:(NSString* )hexString {
    
    
    if (!_bluePointdrawArr2) {
        _bluePointdrawArr2 = [NSMutableArray array];
    }
    
    NSMutableArray *numberArr = [NSMutableArray array];
    //    转换的24个点
    NSMutableArray *pointArr = [NSMutableArray array];
    
    
    //    初始的18点
    int j = 0;
    //  长度 - 1  因为最后一个字符是 '>' 不要的
    for(int i = 5;i < [hexString length] - 1;i ++)
        
    {
        int int_ch; /// 两位16进制数转化后的10进制数
        unichar hex_char1 = [hexString characterAtIndex:i]; ////两位16进制数中的第一位(高位*16)
        
        //        碰到空格 置为空
        if (hex_char1 == ' ') {
            hex_char1 = [hexString characterAtIndex:1 + i];
            //            NSLog(@"碰到一个空格");
            i++;
        }
        
        int int_ch1;
        
        if(hex_char1 >= '0' && hex_char1 <='9')
            
            int_ch1 = (hex_char1-48)*16;   //// 0 的Ascll - 48
        
        else if(hex_char1 >= 'A' && hex_char1 <='F')
            
            int_ch1 = (hex_char1-55)*16; //// A 的Ascll - 65
        
        else
            
            int_ch1 = (hex_char1-87)*16; //// a 的Ascll - 97
        
        i++;
        
        unichar hex_char2 = [hexString characterAtIndex:i]; ///两位16进制数中的第二位(低位)
        //
        int int_ch2;
        
        if(hex_char2 >= '0' && hex_char2 <='9')
            
            int_ch2 = (hex_char2-48); //// 0 的Ascll - 48
        
        else if(hex_char1 >= 'A' && hex_char1 <='F')
            
            int_ch2 = hex_char2-55; //// A 的Ascll - 65
        
        else
            
            int_ch2 = hex_char2-87; //// a 的Ascll - 97
        
        int_ch = int_ch1+int_ch2;
        //
        
        
        [numberArr addObject:[NSNumber numberWithInt:int_ch]];
        j++;
        
    }
    //    这数组中得18个点 三三一组 组成四个点 然后合成24个点
    //    然后就是24个点 两两一组 组成12个点
    
    //    A'
    int aa = 0;
    int bb = 0;
    int cc = 0;
    int dd = 0;
    if (numberArr.count) {
        for (int i = 0; i <= numberArr.count - 3; i = i + 3) {
            
            int a = [numberArr[i] intValue];
            int b = [numberArr[i + 1] intValue];
            int c = [numberArr[i + 2] intValue];
            
            aa = ((a & 0x80) | ((a & 0x7c)>>2));
            //            修改aa
            if (aa != 0) {
                aa = (0xe0)|((a & 0x7c)>>2);
                
            } else {
                aa = ((a & 0x7c)>>2);
            }
            
            bb = (((a & 0x03) << 6) | ((b & 0xf0) >> 2));
            cc = (((b & 0x08)<< 4) | ((b & 0x07) << 2) | ((c & 0xc0) >> 6));
            //            修改cc
            if (cc != 0) {
                cc = (0xe0 | (b & 0x07)<<2) | ((c & 0xc0)>>6);
            } else {
                cc = ((b & 0x07)<<2) | ((c & 0xc0)>>6);
            }
            
            dd = ((c & 0x3f) << 2);
            
            //            [pointArr addObject:[NSNumber numberWithInt:aa]];
            //            [pointArr addObject:[NSNumber numberWithInt:bb]];
            //            [pointArr addObject:[NSNumber numberWithInt:cc]];
            //            [pointArr addObject:[NSNumber numberWithInt:dd]];
            int num1 = ((aa << 8) | bb);
            int num2 = ((cc << 8) | dd);
            
            [pointArr addObject:[NSNumber numberWithInt:num1]];
            [pointArr addObject:[NSNumber numberWithInt:num2]];
        }
    }
    //    pointArr 包含了24个点 这个要转换成12个数
    if (pointArr[5]) {
        [pointArr removeObjectAtIndex:5];
        
    }
    if (pointArr[10]) {
        [pointArr removeObjectAtIndex:10];
        
    }
    
    NSArray *tempArr = [NSArray arrayWithArray:pointArr];
    
    [_bluePointdrawArr2 addObjectsFromArray:tempArr];
    if (_bluePointdrawArr2.count / TEST_LEN >= 1) {
        //        [self dealData];
        if (!_chanel2Arr) {
            _chanel2Arr = [[NSMutableArray alloc]init];
        }
        NSArray *arr = [_bluePointdrawArr2 subarrayWithRange:NSMakeRange(0, TEST_LEN)];
        NSMutableArray *ECGarr = [NSMutableArray arrayWithArray:[self ECGmain:arr chanel:1]];
        
        [_chanel2Arr addObjectsFromArray:ECGarr];
//        [_ECGDataArrWithArr addObjectsFromArray:ECGarr];

        
        //        如果缓存的数据太多 就删除一部分 保证显示的尽量都是实时数据
        if (_chanel2Arr.count > 2000) {
            [_chanel2Arr removeObjectsInRange:NSMakeRange(0, _chanel2Arr.count/2)];
        }
        //        通过数据 计算心率 数据长度 不足1250 计算不出来心率 所以 对ECGarr 进行处理
//        if (!_HrateArr) {
//            _HrateArr = [NSMutableArray array];
//        }
//        if (_HrateArr.count < Hrate_TEST_LEN) {
//            [_HrateArr addObjectsFromArray:ECGarr];
//        } else {
//            double ecgData[Hrate_TEST_LEN];
//            for (int i = 0; i < Hrate_TEST_LEN; i++) {
//                ecgData[i] = [_HrateArr[i] doubleValue];
//            }
//            
//            self.heartRate = hrate_detect(ecgData,Hrate_TEST_LEN);
//            //        NSLog(@"获取的当前心率>> %d",self.heartRate);
//            if (self.heartRate < 0) {
//                _heartRate = 0 ;
//            }
//            [_HrateArr removeObjectsInRange:NSMakeRange(0,Hrate_TEST_LEN )];
//            
//        }
        
        [_bluePointdrawArr2 removeObjectsInRange:NSMakeRange(0, TEST_LEN)];
    }
}



#pragma mark 33333
//   将16进制的字符串 转为10进制的数
- (void)convertString3:(NSString* )hexString {
    NSMutableArray *numberArr = [NSMutableArray array];
    //    转换的24个点
    NSMutableArray *pointArr = [NSMutableArray array];
    
    if (!_bluePointdrawArr3) {
        _bluePointdrawArr3 = [[NSMutableArray alloc]init];
        
    }
    //    初始的18点
    int j = 0;
    //  长度 - 1  因为最后一个字符是 '>' 不要的
    for(int i = 5;i < [hexString length] - 1;i ++)
        
    {
        int int_ch; /// 两位16进制数转化后的10进制数
        unichar hex_char1 = [hexString characterAtIndex:i]; ////两位16进制数中的第一位(高位*16)
        
        //        碰到空格 置为空
        if (hex_char1 == ' ') {
            hex_char1 = [hexString characterAtIndex:1 + i];
            //            NSLog(@"碰到一个空格");
            i++;
        }
        
        int int_ch1;
        
        if(hex_char1 >= '0' && hex_char1 <='9')
            
            int_ch1 = (hex_char1-48)*16;   //// 0 的Ascll - 48
        
        else if(hex_char1 >= 'A' && hex_char1 <='F')
            
            int_ch1 = (hex_char1-55)*16; //// A 的Ascll - 65
        
        else
            
            int_ch1 = (hex_char1-87)*16; //// a 的Ascll - 97
        
        i++;
        
        unichar hex_char2 = [hexString characterAtIndex:i]; ///两位16进制数中的第二位(低位)
        //
        int int_ch2;
        
        if(hex_char2 >= '0' && hex_char2 <='9')
            
            int_ch2 = (hex_char2-48); //// 0 的Ascll - 48
        
        else if(hex_char1 >= 'A' && hex_char1 <='F')
            
            int_ch2 = hex_char2-55; //// A 的Ascll - 65
        
        else
            
            int_ch2 = hex_char2-87; //// a 的Ascll - 97
        
        int_ch = int_ch1+int_ch2;
        //
        
        
        [numberArr addObject:[NSNumber numberWithInt:int_ch]];
        j++;
        
    }
    //    这数组中得18个点 三三一组 组成四个点 然后合成24个点
    //    然后就是24个点 两两一组 组成12个点
    
    //    A'
    int aa = 0;
    int bb = 0;
    int cc = 0;
    int dd = 0;
    if (numberArr.count) {
        for (int i = 0; i <= numberArr.count - 3; i = i + 3) {
            
            int a = [numberArr[i] intValue];
            int b = [numberArr[i + 1] intValue];
            int c = [numberArr[i + 2] intValue];
            
            aa = ((a & 0x80) | ((a & 0x7c)>>2));
            //            修改aa
            if (aa != 0) {
                aa = (0xe0)|((a & 0x7c)>>2);
                
            } else {
                aa = ((a & 0x7c)>>2);
            }
            
            bb = (((a & 0x03) << 6) | ((b & 0xf0) >> 2));
            cc = (((b & 0x08)<< 4) | ((b & 0x07) << 2) | ((c & 0xc0) >> 6));
            //            修改cc
            if (cc != 0) {
                cc = (0xe0 | (b & 0x07)<<2) | ((c & 0xc0)>>6);
            } else {
                cc = ((b & 0x07)<<2) | ((c & 0xc0)>>6);
            }
            
            dd = ((c & 0x3f) << 2);
            
            //            [pointArr addObject:[NSNumber numberWithInt:aa]];
            //            [pointArr addObject:[NSNumber numberWithInt:bb]];
            //            [pointArr addObject:[NSNumber numberWithInt:cc]];
            //            [pointArr addObject:[NSNumber numberWithInt:dd]];
            int num1 = ((aa << 8) | bb);
            int num2 = ((cc << 8) | dd);
            
            [pointArr addObject:[NSNumber numberWithInt:num1]];
            [pointArr addObject:[NSNumber numberWithInt:num2]];
        }
    }
    //    pointArr 包含了24个点 这个要转换成12个数
    if (pointArr[5]) {
        [pointArr removeObjectAtIndex:5];
        
    }
    if (pointArr[10]) {
        [pointArr removeObjectAtIndex:10];
        
    }
    
    
    NSArray *tempArr = [NSArray arrayWithArray:pointArr];
    
    [_bluePointdrawArr3 addObjectsFromArray:tempArr];
    if (_bluePointdrawArr3.count / TEST_LEN >= 1) {
        NSArray *arr = [_bluePointdrawArr3 subarrayWithRange:NSMakeRange(0, TEST_LEN)];
        NSMutableArray *ECGarr = [NSMutableArray arrayWithArray:[self ECGmain:arr chanel:2]];
        if (!_chanel3Arr) {
            _chanel3Arr = [[NSMutableArray alloc]init];
        }
        [_chanel3Arr addObjectsFromArray:ECGarr];
        
        //        如果缓存的数据太多 就删除一部分 保证显示的尽量都是实时数据
        if (_chanel3Arr.count > 2000) {
            [_chanel3Arr removeObjectsInRange:NSMakeRange(0, _chanel1Arr.count/2)];
        }
        //        通过数据 计算心率 数据长度 不足1250 计算不出来心率 所以 对ECGarr 进行处理
//        if (!_HrateArr) {
//            _HrateArr = [NSMutableArray array];
//        }
//        if (_HrateArr.count < Hrate_TEST_LEN) {
//            [_HrateArr addObjectsFromArray:ECGarr];
//        } else {
//            double ecgData[Hrate_TEST_LEN];
//            for (int i = 0; i < Hrate_TEST_LEN; i++) {
//                ecgData[i] = [_HrateArr[i] doubleValue];
//            }
//            
//            self.heartRate = hrate_detect(ecgData,Hrate_TEST_LEN);
//            //        NSLog(@"获取的当前心率>> %d",self.heartRate);
//            if (self.heartRate < 0) {
//                _heartRate = 0 ;
//            }
//            [_HrateArr removeObjectsInRange:NSMakeRange(0,Hrate_TEST_LEN )];
//        }
        
        [_bluePointdrawArr3 removeObjectsInRange:NSMakeRange(0, TEST_LEN)];
    }
}






//   将16进制的字符串 转为10进制的数
- (int)convertStringToInt:(NSString* )hexString {
    int number = 0;
    
    //  长度 - 1  因为最后一个字符是 '>' 不要的
    for(int i = 0;i < [hexString length];i ++)
        
    {
        unichar hex_char1 = [hexString characterAtIndex:i]; ////两位16进制数中的第一位(高位*16)
        
        //        碰到空格 置为空
        if (hex_char1 == ' ') {
            hex_char1 = [hexString characterAtIndex:1 + i];
            //            NSLog(@"碰到一个空格");
            i++;
        }
        
        int int_ch1;
        
        if(hex_char1 >= '0' && hex_char1 <='9')
            
            int_ch1 = (hex_char1-48);   //// 0 的Ascll - 48
        
        else if(hex_char1 >= 'A' && hex_char1 <='F')
            
            int_ch1 = (hex_char1-55); //// A 的Ascll - 65
        
        else
            
            int_ch1 = (hex_char1-87); //// a 的Ascll - 97
        
        number += int_ch1 << 4 *([hexString length] - 1);
        
        
        
    }
    return number;
}
#pragma mark 将两位字符串 转成10进制的数
//   将16进制的2位字符串 转为10进制的数
- (int)convert2StringToInt:(NSString* )hexString {
    int number = 0;
    
    //  长度 - 1  因为最后一个字符是 '>' 不要的
    for(int i = 0;i < [hexString length];i ++)
        
    {
        unichar hex_char1 = [hexString characterAtIndex:i]; ////两位16进制数中的第一位(高位*16)
        
        //        碰到空格 置为空
        if (hex_char1 == ' ') {
            hex_char1 = [hexString characterAtIndex:1 + i];
            //            NSLog(@"碰到一个空格");
            i++;
        }
        
        int int_ch1;
        
        if(hex_char1 >= '0' && hex_char1 <='9')
            
            int_ch1 = (hex_char1-48)*16;   //// 0 的Ascll - 48
        
        else if(hex_char1 >= 'A' && hex_char1 <='F')
            
            int_ch1 = (hex_char1-55)*16; //// A 的Ascll - 65
        
        else
            
            int_ch1 = (hex_char1-87)*16; //// a 的Ascll - 97
        
        i++;//第二个数 低位
        hex_char1 = [hexString characterAtIndex:i];
        int int_ch2;
        
        if(hex_char1 >= '0' && hex_char1 <='9')
            
            int_ch2 = (hex_char1-48);   //// 0 的Ascll - 48
        
        else if(hex_char1 >= 'A' && hex_char1 <='F')
            
            int_ch2 = (hex_char1-55); //// A 的Ascll - 65
        
        else
            
            int_ch2 = (hex_char1-87); //// a 的Ascll - 97

          number = int_ch1 + int_ch2;
    }

    return number;
}


#pragma mark 设备信息使用提示
//设备信号弱提示音 电量低 断开 脱落
//@property (nonatomic, assign) BOOL isSignalWeak, isElectricLow, isDisconnected, isFall;
- (void)warningForSianalWeak{
    
    [self playWavWithName:@"SignalWeak"];
  
}
- (void)warningForElectricLow{
    
   [self playWavWithName:@"ElectricLow"];
}
- (void)warningForDisconnected{
    [self playWavWithName:@"Disconnected"];
    
}
- (void)warningForFall{
    [self playWavWithName:@"Fall"];
    
}

//根据文件名 播放系统声音
- (void)playWavWithName:(NSString *)name{
//提示音 计数  从0开始
    _noteCount = 0;
    
    NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@"wav"];
    if (path) {
        //注册声音到系统
        AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:path],&shake_sound_male_id);
        AudioServicesPlaySystemSound(shake_sound_male_id);
        //        AudioServicesPlaySystemSound(shake_sound_male_id);//如果无法再下面播放，可以尝试在此播放
    }
    AudioServicesPlaySystemSound(shake_sound_male_id);   //播放注册的声音，（此句代码，可以在本类中的任意位置调用，不限于本方法中）
    
//        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);   //让手机震动

    //如果需要在播放完之后执行某些操作，可以调用如下方法注册一个播放完成回调函数
    NSTimer *timer1 = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(soundCompleteCallback:) userInfo:name repeats:YES];
    
   // NSTimer *timer1 = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(soundCompleteCallback:) userInfo:nil repeats:YES];
    [timer1 fire];
    
//    1.关于提示音
//    需求变更为：信号弱响一声，电量低连响二声，断开音连响三声，脱落音连响四声。如果同时并发提示音，则进行阻塞，然后依次提示响声。
//                                关于间隔，不另做间隔时间。根据现在间隔，信号弱与电量低大约为10秒间隔，断开与脱落则是发现立即提示。
    
}

- (void) soundCompleteCallback:(NSTimer *)timer1{

//    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);  //震动
    
//    判断要播放的是谁的声音
    if ([timer1.userInfo isEqualToString:@"Fall"] && _isFall == YES) {
        AudioServicesPlaySystemSound(shake_sound_male_id);  // 播放系统声音 这里的sound是我自定义的，不要copy哈，没有的
        _noteCount++;
        NSLog(@"%@",timer1.userInfo);

        if (_noteCount == 4) {
            [timer1 invalidate];
            _noteCount=0;
              return;
            
        }

    }
    if ([timer1.userInfo isEqualToString:@"Disconnected"] && _isDisconnected == YES) {
        AudioServicesPlaySystemSound(shake_sound_male_id);  // 播放系统声音 这里的sound是我自定义的，不要copy哈，没有的
        _noteCount++;
        NSLog(@"%@",timer1.userInfo);

        if (_noteCount == 3) {
            _noteCount=0;
            [timer1 invalidate];
            return;
        }

    }
    if ([timer1.userInfo isEqualToString:@"ElectricLow"] && _isElectricLow == YES) {
        AudioServicesPlaySystemSound(shake_sound_male_id);  // 播放系统声音 这里的sound是我自定义的，不要copy哈，没有的
        _noteCount++;
        NSLog(@"%@",timer1.userInfo);

        if (_noteCount == 2) {
            _noteCount=0;
            [timer1 invalidate];
              return;
        }
    }
    if ([timer1.userInfo isEqualToString:@"SignalWeak"] && _isSignalWeak == YES) {
        AudioServicesPlaySystemSound(shake_sound_male_id);  // 播放系统声音 这里的sound是我自定义的，不要copy哈，没有的
        NSLog(@"%@",timer1.userInfo);
        _noteCount=0;
        [timer1 invalidate];
          return;
    }

}

#pragma mark 调用C方法 处理蓝牙数据

- (NSArray *)ECGmain:(NSArray *)tempArr chanel:(int)chanel
{
    //    返回处理的数据
    NSMutableArray *outPutArr = [NSMutableArray array];
    
    ECG_E     rc;
    
//    
    short input[TEST_LEN*3];
    short output[TEST_LEN*3];
    int i,j;
    unsigned int cn;
    
    if (ECG_INIT[chanel] == NULL) {
        
        //for(i=0;i<ECG_CHs;i++)
        //{
            
            ECG_INIT[chanel] = ecg_init(chanel);
            
            if( ECG_INIT[chanel] == NULL)
            {
                //            ECG_LOG("ECG CH %d init failed\n",i);
                return 0;
            }
        //}

    }
    

    
        for(j=0;j<TEST_LEN;j++)
        {
              input[j] = htons([tempArr[j] intValue]);
        }
    
    cn = 0;
    
    //while(1)
    {
        int outlen;
        
     
        {
            rc = ecg_input(ECG_INIT[chanel], input , TEST_LEN * 2, output, &outlen);

//            rc = ecg_input(hnd[i], input + i*TEST_LEN , TEST_LEN * 2, output + i*TEST_LEN, &outlen);
            if(rc < ECG_OK)
            {
                goto out;
            }
            else if(rc > 0)
            {
            }
            
            if( outlen > 0) {
                for(j=0;j<outlen/2;j++)
                {
                    //                    得到的输出数组
                    [outPutArr addObject:[NSNumber numberWithShort:ntohs(output[j])]];
                }
                return outPutArr;
            }
        }
        
        
        
    }
    out:
    //for(i=0;i<ECG_CHs;i++)
        ecg_close(ECG_INIT[chanel]);
    
//    ECG_LOG("test program exit\n");
    
    return 0;
}

#pragma mark  header
- (void)creatECGDataTofileWithBlueToothdata:(NSArray *)ECGdataArr{
    
    
//    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//    // 创建异步任务
//    // 上传    测速数据
//    dispatch_async(queue, ^{
        self.muData = [[NSMutableData alloc]init];
        //
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
        //    设置时间格式
        formatter.dateFormat = @"yyyyMMddHHmm";
        
        NSString *fileName = [formatter stringFromDate:[NSDate date]];
        
        NSString *filePath =[NSString stringWithFormat:@"%@/%@.dat",self.filePath,fileName];
        //    NSString *paths = [NSString stringWithFormat:@"%@%@",filePath,fileName];
        //
        if ( ![fileManager fileExistsAtPath:filePath]
            ) {
            
            //            FMDB 是根据路径操作的 所以先找到路径
            NSString *nameList = [NSString stringWithFormat:@"ECGDatalist.db"];
            
            NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:nameList];
            
            //  根据路径去创建一个数据库
            _db = [FMDatabase databaseWithPath:path];
            
            
            if ([_db open]) {
                NSLog(@"数据库打开成功");
            }else
            {
                NSLog(@"数据库打开失败");
            }
            
            //            第一次写 文件 加入 beginTime 用插入字段
            formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss.SSS";
            
            NSString *beginTime = [formatter stringFromDate:[NSDate date]];
            [_db executeUpdate:@"INSERT INTO APPInformationlist (FileName,BeginDT,EndDT,DeviceID,UserID) VALUES (?,?,?,?,?)",fileName,beginTime,beginTime,beginTime,beginTime];
            
            
            [fileManager createFileAtPath:filePath contents:nil attributes:nil];
            //            文件第一次创建 需要添加header设置
            
            //    NSString *str = @"123456789  放到数组里面
            //     考虑到这些数据 以后可能要修改 是不是应该
            
            for (int i  = 0; i < 2<<6 ; i ++) {
                long int n = 0x01;
                switch (i) {
                    case 0:{   //版本号
                        n = 0x01;
                        NSData *data = [NSData dataWithBytes:&n length:1];
                        [self.muData appendData:data];
                        break;
                    }
                    case 1:{
                        n = 0x3f;//control
                        NSData *data = [NSData dataWithBytes:&n length:1];
                        [self.muData appendData:data];
                        break;
                    }
                    case 2:{//lenth
                        n = 0x07;
                        NSData *data = [NSData dataWithBytes:&n length:1];
                        [self.muData appendData:data];
                        break;
                    }
                    case 3:{//FirstSEQ
                        n = 0x00;
                        NSData *data = [NSData dataWithBytes:&n length:5];
                        [self.muData appendData:data];
                        break;
                    }
                    case 8:{//DeviceID
                        n = 0xffffffff;
                        NSData *data = [NSData dataWithBytes:&n length:4];
                        [self.muData appendData:data];
                        break;
                    }
                    case 0x0c:{//Boot Version
                        n = 0x04030201;
                        NSData *data = [NSData dataWithBytes:&n length:4];
                        [self.muData appendData:data];
                        break;
                    }
                    case 0x10:{//Firmware Ver
                        n = 0x04030201;
                        NSData *data = [NSData dataWithBytes:&n length:4];
                        [self.muData appendData:data];
                        break;
                    }
                    case 0x14:{//ECG_Channels
                        n = 0x03;
                        NSData *data = [NSData dataWithBytes:&n length:1];
                        [self.muData appendData:data];
                        break;
                    }
                    case 0x15:{//ECG_Resolution
                        n = 0x10;
                        NSData *data = [NSData dataWithBytes:&n length:1];
                        [self.muData appendData:data];
                        break;
                    }
                    case 0x16:{//ECG_Frequency
                        n = 0x7d00;
                        NSData *data = [NSData dataWithBytes:&n length:2];
                        [self.muData appendData:data];
                        break;
                    }
                    default:
                        break;
                        
                }
                
                if ((i >= 0x18)) {
                    n = 0xff;
                    NSData *data = [NSData dataWithBytes:&n length:1];
                    [self.muData appendData:data];
                }
            }
            
            self.fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:filePath];
#pragma mark 数据块
            [self.fileHandle seekToEndOfFile];
            //    Version
            int n = 0x00;
            {
                n = 0x01;
                NSData *data = [NSData dataWithBytes:&n length:1];
                [self.muData appendData:data];
            }
            //    Control
            {
                n = 0x007f;
                NSData *data = [NSData dataWithBytes:&n length:4];
                [self.muData appendData:data];
            }
            //    Length
            {
                n = 0x00;
                NSData *data = [NSData dataWithBytes:&n length:5];
                [self.muData appendData:data];
            }
            
            //    FirstSEQ
            //    Records
            //    拼接
            [self.fileHandle seekToEndOfFile];
            [self.fileHandle writeData:_muData];
            [self.fileHandle closeFile];
            
            //    最后的时候 更新一下 结束的时间
            formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss.SSS";
            
            NSString *endTime = [formatter stringFromDate:[NSDate date]];
            [_db executeUpdate:@"update  APPInformationlist set EndDT = ? where FileName = ?",endTime,fileName];
            return;
        }
        self.fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:filePath];
        //这里是已经存在了这个文件 就直接写入 ECG数据
        NSMutableData *tempData = [NSMutableData data];
        for (int i = 0 ; i < ECGdataArr.count; i++) {
            [tempData appendData:ECGdataArr[i]];
        }
        
        
        [self.fileHandle seekToEndOfFile];
        [self.fileHandle writeData:tempData];
        
        //    最后的时候 更新一下 结束的时间
        formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss.SSS";
        
        NSString *endTime = [formatter stringFromDate:[NSDate date]];
        [_db executeUpdate:@"update  APPInformationlist set EndDT = ? where FileName = ?",endTime,fileName];
        [self.fileHandle closeFile];

    
//    });
    
    }
//创建保存ECGData信息的数据表
- (void)ECGDatalist{
    //    我需要创建一张表  存储我每一条记录的开始时间 结束时间
    //    dic[@"UserID"] = userID;
    //    dic[@"DeviceID"] = deviceID;
    //    dic[@"BeginDT"] = @"2016-01-01 00:00:00.000";
    //    dic[@"EndDT"] = @"2018-01-01 01:00:00.000";
    //    dic[@"FileName"] = filenames[i];
    //  创建我们的数据库的路径 同时拼接数据库的文件名称
    NSString *nameList = [NSString stringWithFormat:@"ECGDatalist.db"];
    
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:nameList];
    
    //  根据路径去创建一个数据库
    _db = [FMDatabase databaseWithPath:path];
    NSLog(@">> 地址%@",path);
    
    //    添加键值对
    if ([_db open]) {
        NSLog(@"数据库打开成功");
    }else
    {
        NSLog(@"数据库打开失败");
    }
    //    调用db的executeUpdata 这个方法的参数就是SQL 语句 logName为key
    [_db executeUpdate:@"CREATE TABLE APPInformationlist (FileName text, BeginDT text, EndDT text, DeviceID text, UserID text)"];
    
//    [self creatECGDataTofileWithBlueToothdata:nil];

}



- (NSMutableArray *)ECGDataArrWithArr{

    if (!_ECGDataArrWithArr) {
        _ECGDataArrWithArr = [[NSMutableArray alloc]init];
    }
    return _ECGDataArrWithArr;
}


- (NSMutableArray *)tepArr{

    if (!_tepArr) {
        _tepArr = [[NSMutableArray alloc]init];
    }
    return _tepArr;
}

- (BOOL)isSignalWeak{

    if (!_isSignalWeak) {
        _isSignalWeak = NO;
    }
    return _isSignalWeak;
}
- (BOOL)isElectricLow{

    if (!_isElectricLow) {
        _isElectricLow = NO;
    }
    return _isElectricLow;
}
- (BOOL)isFall{
    if (!_isFall) {
        _isFall = NO;
    }
    return _isFall;
}
- (BOOL)isDisconnected{
    if (!_isConnected) {
        _isConnected = NO;
    }
    return _isConnected;
}
- (BOOL)isGPSON{
    if (!_isGPSON) {
        _isGPSON = NO;
    }
    return _isGPSON;
}






@end
